use std::{
    env::var_os,
    error::Error,
    fs::File,
    io::{BufRead, BufReader, BufWriter, Write},
    path::PathBuf,
};

use brotli_decompressor::Decompressor;

// Use longer literals for better buffering
macro_rules! lit_lines {
    ($($str:literal)* $(,)?) => {{
        concat!($($str, "\n"),* ).as_bytes()
    }};
}

fn main() -> Result<(), Box<dyn Error>> {
    println!("cargo:rerun-if-changed=data/dict");
    println!("cargo:rerun-if-changed=build.rs");

    let data = BufReader::new(Decompressor::new(File::open("data/dict")?, 4096));

    let out_dir = PathBuf::from(var_os("OUT_DIR").unwrap());
    let mut dict_output = BufWriter::new(File::create(out_dir.join("dict.rs"))?);

    dict_output.write_all(lit_lines!(
        "// This file is auto-generated by build.rs"
        "mod dict {"
        "    /// A Chinese to Wade-Giles dictionary"
        "    pub const DICT: &[(&'static str, &'static str)] = &["
    ))?;

    let mut max_len = 0;

    for ele in data.lines() {
        let line = ele?;
        let (word, pron) = line
            .split_once('\t')
            .ok_or_else(|| format!("invalid entry: {:?}", line))?;

        writeln!(dict_output, "        ({:?}, {:?}),", word, pron)?;
        max_len = max_len.max(word.len());
    }
    dict_output.write_all(lit_lines!(
        "    ];"
        "}"
        ""
        "pub use dict::DICT;"
    ))?;

    Ok(())
}
